package com.android.manghe.view.popWindow;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.base.okhttp.okUtil.OKHttpUtil;
import com.android.base.tools.Glide.GlideHelper;
import com.android.base.tools.ToastUtil;
import com.android.manghe.R;
import com.android.manghe.box.model.BoxModel;
import com.android.manghe.cache.UserHolder;
import com.android.manghe.common.model.BaseBack;
import com.android.manghe.common.model.PaymentTypeRes;
import com.android.manghe.common.webview.ERefreshWebType;
import com.android.manghe.common.webview.WebViewActivity;
import com.android.manghe.common.webview.WebViewParameter;
import com.android.manghe.config.Config;
import com.android.manghe.config.ConstantsUrl;
import com.android.manghe.market.model.BoxCheckOrderModel;
import com.android.manghe.mine.adapter.PayAdapter;
import com.android.manghe.utils.WindowUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

/**
 * author : liuwen
 * e-mail : liuwen370494581@163.com
 * time   : 2021/10/26 16:57
 * desc   :
 */
public class OrderSurePopWindow extends PopupWindow {

    private Activity mContext;
    private TextView mTvAgreement, mTvName, mTvTotal, mTvPrice, mTvOk, mTvCoin, mTvCoin2, mTvWithHold,
            mTvFreeCoin, mTvFreeCoin2, mTvAvailableCoins, mTvUserCoins;
    private ImageView mImgSelect, mImgDelete, mImgCover, mImgCoinsSelect;

    private boolean mIsCheck = true, mIsCoinsCheck = true;
    private TextView btnQuantityMinus, tvQuantity, btnQuantityPlus;
    private IOrderSureListener mListener;
    private BoxModel.DataBean mCurrentBox;
    private RecyclerView mRecyclerView;
    private PayAdapter mPayAdapter;
    private List<PaymentTypeRes.DataBean.PaymentBean> mPaymentList;
    private BoxCheckOrderModel.DataBean mOrderModel;
    private RelativeLayout mReCoins;


    public OrderSurePopWindow(Activity activity, BoxModel.DataBean boxModel, BoxCheckOrderModel.DataBean orderModel, List<PaymentTypeRes.DataBean.PaymentBean> paymentList) {
        super(activity);
        mContext = activity;
        this.mCurrentBox = boxModel;
        this.mPaymentList = paymentList;
        this.mOrderModel = orderModel;
        init();
    }

    public void setListener(IOrderSureListener listener) {
        this.mListener = listener;
    }

    private void init() {
        final View popupView = LayoutInflater.from(mContext).inflate(R.layout.layout_order_sure_pop_window, null, false);

        mTvAgreement = popupView.findViewById(R.id.id_tv_agreement);
        mImgSelect = popupView.findViewById(R.id.ivCheck);
        mImgCoinsSelect = popupView.findViewById(R.id.id_img_coins_select);
        mImgDelete = popupView.findViewById(R.id.id_img_delete);
        mImgCover = popupView.findViewById(R.id.ivPic);
        mTvName = popupView.findViewById(R.id.tvGoodName);
        mTvTotal = popupView.findViewById(R.id.id_tv_total);
        mTvOk = popupView.findViewById(R.id.id_tv_ok);
        btnQuantityMinus = popupView.findViewById(R.id.btnQuantityMinus);
        tvQuantity = popupView.findViewById(R.id.tvQuantity);
        btnQuantityPlus = popupView.findViewById(R.id.btnQuantityPlus);
        mRecyclerView = popupView.findViewById(R.id.id_pay_recycler_view);

        mTvCoin = popupView.findViewById(R.id.id_tv_03);
        mTvCoin2 = popupView.findViewById(R.id.id_tv_06);
        mTvFreeCoin = popupView.findViewById(R.id.id_txt_03);
        mTvFreeCoin2 = popupView.findViewById(R.id.id_txt_06);
        mTvWithHold = popupView.findViewById(R.id.id_tv_with_hold);
        mTvPrice = popupView.findViewById(R.id.id_tv_price);
        mTvAvailableCoins = popupView.findViewById(R.id.id_tv_coins_value);
        mTvUserCoins = popupView.findViewById(R.id.id_tv_coins_value_2);
        mReCoins = popupView.findViewById(R.id.id_re_coins);
        GlideHelper.loadWithHolderErr(mContext, mCurrentBox.cover_pic, mImgCover);
        mTvName.setText(mCurrentBox.name);

        popupView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        this.setContentView(popupView);
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setFocusable(true);
        this.setOutsideTouchable(true);
        this.setBackgroundDrawable(new ColorDrawable());
        this.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                dismiss();
                WindowUtils.backgroundAlpha(mContext, 1f);
            }
        });


        mImgSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mIsCheck = !mIsCheck;
                mImgSelect.setImageResource(mIsCheck ? R.mipmap.tick_click_white : R.mipmap.icon_tick_default);

            }
        });

        mReCoins.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getBoxCheckOrder(mOrderModel.manghe_cat_id + "", mOrderModel.buy_num,!mIsCoinsCheck?1:0);


            }
        });


        mImgDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
                WindowUtils.backgroundAlpha(mContext, 1f);
            }
        });

        mTvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //立即支付
                if (mIsCheck) {
                    if (mListener != null) {
                        dismiss();
                        mListener.pay(mOrderModel, mPayAdapter.getSelectedPayment(), mIsCoinsCheck ? 1 : 0);
                    }
                } else {
                    ToastUtil.showLong(mContext, "请勾选下面选项");
                }
            }
        });

        //减少
        btnQuantityMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        //增加
        btnQuantityPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        initRecyclerView();
        setDate();
        setColorAndEvent();
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mPayAdapter = new PayAdapter(mContext, new ArrayList<>());
        mRecyclerView.setAdapter(mPayAdapter);
        mPayAdapter.update(mPaymentList);
        mPayAdapter.setListener(new PayAdapter.IPayListener() {
            @Override
            public void onClick(PaymentTypeRes.DataBean.PaymentBean item) {
                mPayAdapter.selectedItem(item);
            }
        });
    }

    private void setDate() {
        try {
            if (mOrderModel != null) {
                tvQuantity.setText(mOrderModel.buy_num + "");
                mTvTotal.setText("￥" + mOrderModel.total);
                mTvCoin.setText(mOrderModel.remain_coin + "");
                mTvCoin2.setText(mOrderModel.coin + "");
                mTvFreeCoin.setText(mOrderModel.remain_free_coin + "");
                mTvFreeCoin2.setText(mOrderModel.free_coin + "");
                mTvPrice.setText("￥" + mOrderModel.cash + "");
                mTvWithHold.setText("(已抵扣￥" + mOrderModel.withhold + ")");
                mTvOk.setText("立即支付￥" + mOrderModel.cash);
                if (mOrderModel.score > 0) {
                    mReCoins.setVisibility(View.VISIBLE);
                    mTvAvailableCoins.setText(mOrderModel.score + "");
                    mTvUserCoins.setText(mOrderModel.score_offset + "");
                } else {
                    mReCoins.setVisibility(View.GONE);
                }
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public int getSelectedQuantity(TextView tvQyt) {
        return Integer.parseInt(tvQyt.getText().toString());
    }

    private void setColorAndEvent() {
        SpannableStringBuilder style = new SpannableStringBuilder("盲盒类商品付款后即可完成在线拆盒，不支持7天无理由退货,详情请查看");
        SpannableStringBuilder style2 = new SpannableStringBuilder("《芒铺规则》");
        SpannableStringBuilder style3 = new SpannableStringBuilder("《芒铺服务协议》");
        SpannableStringBuilder style4 = new SpannableStringBuilder("《芒铺支付协议》");
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.blue));
        ForegroundColorSpan foregroundColorSpan2 = new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.blue));
        ForegroundColorSpan foregroundColorSpan3 = new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.blue));

        setTextClickEvent(style2, 0, style2.length(), Config.BOX_RULE_URI, "芒铺规则");//start,end
        setTextClickEvent(style3, 0, style3.length(), Config.BOX_USER_SERVICE_URI, "芒铺服务协议");
        setTextClickEvent(style4, 0, style3.length(), Config.BOX_PAY_URI, "芒铺支付协议");

        style2.setSpan(foregroundColorSpan, 0, style2.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style3.setSpan(foregroundColorSpan2, 0, style3.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style4.setSpan(foregroundColorSpan3, 0, style4.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        style.append(style2).append("、").append(style3).append("和").append(style4);

        mTvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        mTvAgreement.setText(style);
    }

    private void setTextClickEvent(SpannableStringBuilder style, int start, int end, final String uriStr, String title) {
        ClickableSpan clickableSpan1 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                WebViewParameter parameters = new WebViewParameter.WebParameterBuilder()
                        .setUrl(uriStr)
                        .setShowProgress(true)
                        .setCanHistoryGoBackOrForward(true)
                        .setReloadable(true)
                        .setShowWebPageTitle(false)
                        .setReloadType(ERefreshWebType.ClickRefresh)
                        .setCustomTitle(title)
                        .build();

                Intent intent = new Intent(mContext, WebViewActivity.class);
                intent.putExtra("parameters", parameters);
                mContext.startActivity(intent);

            }
        };
        style.setSpan(clickableSpan1, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }


    public void showPopWindow(View view) {
        if (this.isShowing()) {
            this.dismiss();
        } else {
            this.showAtLocation(view, Gravity.BOTTOM, 0, 0);
            WindowUtils.backgroundAlpha(mContext, 0.5f);
        }
    }


    public void close() {
        super.dismiss();
    }

    public interface IOrderSureListener {
        void pay(BoxCheckOrderModel.DataBean model, PaymentTypeRes.DataBean.PaymentBean paymentBean, int use_score);
    }


    //网络层 ===============================================================
    public void getBoxCheckOrder(String manghe_id, int num, int use_score) {
        HashMap<String, String> data = new HashMap<>();
        data.put("id", manghe_id);
        data.put("num", num + "");
        data.put("use_score", use_score + "");
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("UID", UserHolder.getUID(mContext));
        headMap.put("TOKEN", UserHolder.getUserInfo(mContext).TOKEN);
        headMap.put("PLATFORM", "android");
        new OKHttpUtil(mContext).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.Box_Check_Order, headMap)
                .post(data).build()
                .execute(new BaseBack<BoxCheckOrderModel>() {
                    @Override
                    public void onSuccess(Call call, BoxCheckOrderModel res) {
                        if (res != null && res.data != null) {
                            mOrderModel = res.data;
                            mIsCoinsCheck = !mIsCoinsCheck;
                            mImgCoinsSelect.setImageResource(mIsCoinsCheck ? R.mipmap.tick_click : R.mipmap.icon_tick_default);
                            setDate();
                        } else {
                            showCheckTip();
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void showCheckTip() {
        ToastUtil.showLong(mContext, "获取订单失败,请重试");
    }
}
